//
//  CrashSignal.swift
//  swift_review
//
//  Created by Andrew on 2025/1/22.
//

import UIKit

class CrashSignal: NSObject {

}

// 崩溃信息处理方法
func logCrashInfo(message: String) {
    // 这里你可以将崩溃信息保存到文件、数据库或上传到服务器
    print("Crash Info: \(message)")
    
    // 将崩溃信息保存到本地文件
    let crashLogFile = "crash_log.txt"
    let crashLogMessage = "\(Date()) - \(message)\n"
    
    if let documentDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let fileURL = documentDir.appendingPathComponent(crashLogFile)
        
        if FileManager.default.fileExists(atPath: fileURL.path) {
            // 如果文件已存在，追加信息
            if let fileHandle = try? FileHandle(forWritingTo: fileURL) {
                fileHandle.seekToEndOfFile()
                if let data = crashLogMessage.data(using: .utf8) {
                    fileHandle.write(data)
                    fileHandle.closeFile()
                }
            }
        } else {
            // 文件不存在时，创建新文件
            try? crashLogMessage.write(to: fileURL, atomically: true, encoding: .utf8)
        }
    }
}

// 信号处理函数
func handleSignal(signal: Int32) {
    var signalName: String
    
    switch signal {
    case SIGABRT:
        signalName = "SIGABRT"
    case SIGSEGV:
        signalName = "SIGSEGV"
    case SIGFPE:
        signalName = "SIGFPE"
    default:
        signalName = "Unknown signal"
    }
    
    // 获取堆栈信息
    let stackSymbols = Thread.callStackSymbols.joined(separator: "\n")
    
    // 生成崩溃信息
    let crashInfo = "Caught signal: \(signalName)\nStack Trace:\n\(stackSymbols)"
    
    // 打印并记录崩溃信息
    logCrashInfo(message: crashInfo)
}

// 捕获信号的方法
func setupSignalHandlers() {
    // 捕获常见的信号崩溃
    signal(SIGABRT, handleSignal)
    signal(SIGSEGV, handleSignal)
    signal(SIGFPE, handleSignal)
    signal(SIGILL, handleSignal)  // Invalid instruction
    signal(SIGBUS, handleSignal)  // Bus error (memory access)
    signal(SIGPIPE, handleSignal) // Broken pipe
    // 你可以根据需要添加更多的信号类型
}

// 在应用启动时调用此方法
func setupCrashHandler() {
    setupSignalHandlers()
}

